package com.gljx.web.controller;

import com.gljx.util.*;
import com.gljx.web.Entity.*;
import com.gljx.web.dao.DropexercisetwoMapper;
import com.gljx.web.service.CustomLogService;
import com.gljx.web.service.DepartmentService;
import com.gljx.web.service.DropexerciseTwoService;
import com.gljx.web.service.SharecartworegService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2017/11/20 0020.
 */
@Controller
@RequestMapping("/")
public class DropexerciseTwoContraller {

    @Autowired
    DropexerciseTwoService dropexerciseTwoService;
    @Autowired
    DepartmentService departmentService;
    @Autowired
    CustomLogService customLogService;
    @Autowired
    ExerciseCarPlanController exerciseCarPlanController;
    @Autowired
    DropexercisetwoMapper dropexercisetwoMapper;

    /**
     * @Author lcx
     * @Date 2017/11/20 0020 上午 10:43
     * 查询科目二分车列表
     */
    @RequestMapping("/queryDropexercisetwo/look.action")
    public String queryDropexercisetwo(HttpServletRequest request, @RequestParam(value = "fnumber", defaultValue = "") String fnumber
            , @RequestParam(value = "fdescription", defaultValue = "") String fdescription
            , @RequestParam(value = "cfstudentname", defaultValue = "") String cfstudentname
            , @RequestParam(value = "beginTime", defaultValue = "") String beginTime
            , @RequestParam(value = "endTime", defaultValue = "") String endTime
            , @RequestParam(value = "state", defaultValue = "") String state
            , @RequestParam(value = "alertType", defaultValue = "") String alertType) {

        PageBean<Dropexercisetwo> pb = new PageBean<>();
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        try {
            fnumber = fnumber.trim();//去空格
            fdescription = fdescription.trim();
            cfstudentname = cfstudentname.trim();
            //第一次进来
            if ("first".equals(state)) {
                beginTime = TimeFormat.getMonth();
                endTime = TimeFormat.getNowTime();
                pb = getPageBean(request, user.getFcompanyid(), fnumber, fdescription, cfstudentname, beginTime, endTime, "");
            } else if ("".equals(state) && "".equals(beginTime) || "".equals(endTime)) {
                pb = getPageBean(request, user.getFcompanyid(), fnumber, fdescription, cfstudentname, beginTime, endTime, null);
            } else {
                pb = getPageBean(request, user.getFcompanyid(), fnumber, fdescription, cfstudentname, beginTime, endTime, "");

            }
            //获取当前分页的值
            List<Dropexercisetwo> dropexercisetwoList = pb.getBeanList();
            //把获取到的数据传回页面
            for (Dropexercisetwo dropexercisetwo : dropexercisetwoList) {
                //查询学员信息
                dropexercisetwo.setDropexercisetwoentryList(dropexerciseTwoService.selectDropexercisetwoentryByFid(dropexercisetwo.getFid(), cfstudentname));
            }
            //合计信息总条数
            String messageAmount="共有"+pb.getTr()+"条信息";

            //返回界面的搜索条件
            request.setAttribute("messageAmount",messageAmount);
            request.setAttribute("fnumber", fnumber);
            request.setAttribute("fdescription", fdescription);
            request.setAttribute("cfstudentname", cfstudentname);
            request.setAttribute("beginTime", beginTime);
            request.setAttribute("endTime", endTime);

            request.setAttribute("dropexercisetwoList", dropexercisetwoList);
            request.setAttribute("pb", pb);
            request.setAttribute("alertType", alertType);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "/backHome/practiseCAR/DropexerciseTwo/DropexerciseTwoList";
    }

    public PageBean<Dropexercisetwo> getPageBean(HttpServletRequest request, String companyId, String fnumber,
                                                 String fdescription, String cfstudentname,
                                                 String beginTime, String endTime, String state) throws Exception {

        int offset;//从第几条数据开始加载
        if (request.getParameter("pager.offset") == null) {
            offset = 0;
        } else {
            offset = Integer.parseInt(request.getParameter("pager.offset"));
        }
        //拼接SQL语句
        StringBuffer psql = new StringBuffer();
        if (state == null) {
            psql.append("SELECT DISTINCT" +
                    "  d.fid," +
                    "  d.FNUMBER, " +
                    "  TO_CHAR(d.FBIZDATE, 'YYYY-MM-DD') fbizdate, " +
                    "  d.FDESCRIPTION, " +
                    "  u.NAME                            checkName, " +
                    "  u1.NAME                           createName, " +
                    "  d.CFBILLSTATE," +
                    "   d.FCREATETIME," +
                    "   TO_CHAR(d.FBIZDATE, 'YYYY-MM-DD') " +
                    "   FROM CT_DS_DROPEXERCISETWO D" +
                    "  LEFT JOIN T_E_USER u ON d.FAUDITORID = u.FID " +
                    "  LEFT JOIN T_E_USER u1 ON d.FCREATORID = u1.FID" +
                    "  LEFT JOIN CT_DS_DROPEXERCISETWOENTRY d2 on d.fid = d2.FPARENTID" +
                    "  LEFT JOIN CT_DS_STUDENT S ON d2.CFSTUDENTID = S.FID" +
                    " where d.FCONTROLUNITID= '" + companyId + "'");
            if (!"".equals(fnumber)) {
                psql.append(" and d.FNUMBER LIKE '%" + fnumber + "%' ");
            }
            if (!"".equals(fdescription)) {
                psql.append(" and d.FDESCRIPTION LIKE '%" + fdescription + "%' ");
            }
            if (!"".equals(cfstudentname)) {
                psql.append(" and S.FNAME_L2 LIKE '%" + cfstudentname + "%' ");
            }
            psql.append(" ORDER BY d.FCREATETIME DESC");
        } else {
            psql.append("SELECT DISTINCT" +
                    "  d.fid," +
                    "  d.FNUMBER, " +
                    "  TO_CHAR(d.FBIZDATE, 'YYYY-MM-DD') fbizdate, " +
                    "  d.FDESCRIPTION, " +
                    "  u.NAME                            checkName, " +
                    "  u1.NAME                           createName, " +
                    "  d.CFBILLSTATE," +
                    "   d.FCREATETIME," +
                    "   TO_CHAR(d.FBIZDATE, 'YYYY-MM-DD') " +
                    "   FROM CT_DS_DROPEXERCISETWO D" +
                    "  LEFT JOIN T_E_USER u ON d.FAUDITORID = u.FID " +
                    "  LEFT JOIN T_E_USER u1 ON d.FCREATORID = u1.FID" +
                    "  LEFT JOIN CT_DS_DROPEXERCISETWOENTRY d2 on d.fid = d2.FPARENTID" +
                    "  LEFT JOIN CT_DS_STUDENT S ON d2.CFSTUDENTID = S.FID" +
                    " where d.FCONTROLUNITID= '" + companyId + "'");
            if (!"".equals(fnumber)) {
                psql.append(" and d.FNUMBER LIKE '%" + fnumber + "%' ");
            }
            if (!"".equals(fdescription)) {
                psql.append(" and d.FDESCRIPTION LIKE '%" + fdescription + "%' ");
            }
            if (!"".equals(cfstudentname)) {
                psql.append(" and S.FNAME_L2 LIKE '%" + cfstudentname + "%' ");
            }
            psql.append(" and (d.FBIZDATE BETWEEN to_date('" + beginTime + "', 'YYYY/MM/DD') AND to_date('" + endTime + "', 'YYYY/MM/DD')) " +
                    " ORDER BY d.FCREATETIME DESC");
        }

        int psize = 100; //每页显示数
        int pindex = offset / psize;//+1  页码从0开始
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = dropexerciseTwoService.selectPage(pindex, psql.toString(), psize);
        PageBean<Dropexercisetwo> pb = new PageBean<>();
        pb.setPc(pindex); //页码
        Map<String, Object> paramMapCount = getPageBeanCount(psql.toString()); //取记录总数
        pb.setTr((int) paramMapCount.get("Pcount")); //记录总数
        pb.setPs(psize);
        pb.setBeanList((List<Dropexercisetwo>) paramMap.get("v_cur")); //每页数据集
        return pb;
    }

    /**
     * 取记录总数 dmz 20160921
     *
     * @param psql SQL语句
     * @return Map
     * @throws Exception
     */
    public Map<String, Object> getPageBeanCount(String psql) throws Exception {

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = dropexerciseTwoService.selectPageCount(psql);
        return paramMap;
    }


    /**
     * @Author lcx
     * @Date 2017/11/27 0027 上午 8:49
     * 跳转到添加科目二退练页面
     */
    @RequestMapping(value = "/go_add_Dropexercisetwo")
    public String goAddDropexercisetwo(HttpServletRequest request, String alertType) throws Exception {
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        Department department = departmentService.queryAdminByFid(user.getFcompanyid());

        /*String number = customLogService.selectFunmber("CT_DS_DROPEXERCISETWO",user.getFcompanyid());*/
        String fnumber = GetFnumber.fnumbers("KMETL");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String fbizdate = sdf.format(new Date());

        //查询练车时间
        Map map3 = exerciseCarPlanController.getExerciseCarPlan(request, "", "", "0");

        request.setAttribute("fbizdate", fbizdate);
        request.setAttribute("createName", user.getName());
        request.setAttribute("fnumber", fnumber);
        request.setAttribute("department", department.getFnameL2());
        request.setAttribute("pb3", map3.get("pb"));
        request.setAttribute("exerciseCarPlans", map3.get("sList"));

        request.setAttribute("alertType", alertType);

        return "/backHome/practiseCAR/DropexerciseTwo/DropexerciseTwoAdd";


    }


    @RequestMapping(value = "/add_dropexercisetwo")
    public String addShareCarTwoReg(HttpServletRequest request, Dropexercisetwo dropexercisetwo, @RequestParam(defaultValue = "0") String state) {

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        //公司id
        dropexercisetwo.setCfficompanyid(user.getFcompanyid());
        //控制单元id
        dropexercisetwo.setFcontrolunitid(user.getFcompanyid());
        //获取当前修改时间
        String createTime = TimeFormat.timeFormat(new Date());
        //创建时间
        dropexercisetwo.setFcreatetime(createTime);
        //创建人id
        dropexercisetwo.setFcreatorid(user.getFid());


        //获取子类
        String[] cfstudentid = request.getParameterValues("cfstudentid");//学生id
        String[] cfstudentName = request.getParameterValues("cfstudentName");//学生
        String[] cfstudentno = request.getParameterValues("cfstudentno");
        String[] cfidcardno = request.getParameterValues("cfidcardno");
        String[] cfmobile = request.getParameterValues("cfmobile");
        String[] cfphone = request.getParameterValues("cfphone");
        String[] cfcoachid = request.getParameterValues("cfcoachid");//教练id
        String[] cfcoachName = request.getParameterValues("cfcoachName");//教练
        String[] cfcarpeoplenum = request.getParameterValues("cfcarpeoplenum");
        String[] cflcts = request.getParameterValues("cflcts");
        String[] cftlyy = request.getParameterValues("cftlyy");

        dropexerciseTwoService.adddropexercisetwo(dropexercisetwo, cfstudentid, cfstudentName, cfstudentno,
                cfidcardno, cfmobile, cfphone, cfcoachid, cfcoachName, cfcarpeoplenum, cflcts, cftlyy, state);


        //添加日志
        customLogService.addLog("练车管理", TimeFormat.timeFormat(new Date()) + "对科目二退练新增", null, user.getFid());

        return "redirect:/DrivingSys/go_add_Dropexercisetwo?alertType=bc";
    }


    @RequestMapping(value = "go_update_dropexercisetwo")
    public String goUpdateShareCarTwoReg(HttpServletRequest request, String fid, String xqid) throws Exception {

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        Department department = departmentService.queryAdminByFid(user.getFcompanyid());

        //查询科目二分车信息
        Dropexercisetwo dropexercisetwoList = dropexerciseTwoService.selectDropexercisetwoByFid(fid);

        if (dropexercisetwoList == null) {
            return "/error/not_data";
        }

        //查询练车时间
        Map map3 = exerciseCarPlanController.getExerciseCarPlan(request, "", "", "0");

        //查询是否是经办人
        Axamine axamine = new Axamine();
        request.setAttribute("AuditState", axamine.selectAuditPerson(dropexercisetwoList.getFnumber()));

        request.setAttribute("dropexercisetwoList", dropexercisetwoList);
        request.setAttribute("department", department.getFnameL2());
        request.setAttribute("pb3", map3.get("pb"));
        request.setAttribute("exerciseCarPlans", map3.get("sList"));

        return "/backHome/practiseCAR/DropexerciseTwo/updateDropexerciseTwo";
    }

    /**
     * @Author lcx
     * @Date 2017/11/28 0028 上午 9:01
     * 更新退练信息
     */
    @RequestMapping(value = "/update_dropexercisetwo")
    public String updateRecordin(HttpServletRequest request, Dropexercisetwo dropexercisetwo) {

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");

        //获取当前修改时间
        String createTime = TimeFormat.timeFormat(new Date());
        //修改时间
        dropexercisetwo.setFlastupdatetime(createTime);
        //修改人id
        dropexercisetwo.setFlastupdateuserid(user.getFid());

        addShareCarTwoReg(request, dropexercisetwo, "1");

        return "redirect:/DrivingSys/queryDropexercisetwo/look.action?state=first&alertType=qd";
    }


    /**
     * @Author lcx
     * @Date 2017/11/28 0028 上午 9:02
     * 删除
     */
    @RequestMapping(value = "delete_dropexercisetwo")
    public String deleteDropexercisetwo(HttpServletRequest request, String[] deleteId, String[] fnumber) throws Exception {

        User user = (User) request.getSession().getAttribute("user");

        dropexerciseTwoService.deleteByDropexercisetwoKey(deleteId, fnumber);
        //添加日志
        customLogService.addLog("练车管理", TimeFormat.timeFormat(new Date()) + "对科目二退练进行删除", null, user.getFid());


        return "redirect:/DrivingSys/queryDropexercisetwo/look.action?state=first";
    }


    /**
     * @Author lcx
     * @Date 2017/12/1 0001 下午 4:36
     * state  2为科目二 3为科目三
     */
    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/getPageDropexercise")
    public Map getPageBeanAsDropexercise(HttpServletRequest request, @RequestParam(defaultValue = "", value = "name") String name,
                                         @RequestParam(defaultValue = "", value = "cflcsjid") String cflcsjid, @RequestParam(defaultValue = "0")
                                                 String pindex, @RequestParam(defaultValue = "2", value = "state") String state) throws Exception {


        List<Object> sharecartworegentryList = dropexerciseTwoService.selectByWindowsPageAsSharecartworegentry(name, cflcsjid, state);

        Map stu = new HashMap();
        stu.put("sList", (List<Object>) sharecartworegentryList);


        return stu; //每页数据集;
    }

    /**
     * @Author lcx
     * @Date 2017/11/27 0027 下午 3:03
     * 根据fid查询学生的教练以及学生信息 从科目二分车表中查询
     */
    @RequestMapping(value = "/selStudentsBySharecartwo")
    @ResponseBody
    public Object selPositiongradeById(@RequestParam(value = "id", required = false) String id, @RequestParam(defaultValue = "2", value = "state") String state) throws Exception {
        List<Sharecartworegentry> sharecartworegentryList = new ArrayList<Sharecartworegentry>();
        String[] ids = id.split(",");
        for (int i = 0; i < ids.length; i++) {
            List<Sharecartworegentry> sharecartworegentry = dropexerciseTwoService.selectStudentById(ids[i], state);
            sharecartworegentryList.add(sharecartworegentry.get(0));
        }
        return sharecartworegentryList;
    }

    /**
     * @Author lcx
     * @Date 2018/2/5 0005 上午 10:20
     * 科目二退练流程-审核
     */
    @RequestMapping(value = "/queryDropexercisetwoExamine")
    @ResponseBody
    public ServerResponse examine(HttpServletRequest request, @RequestParam(defaultValue = "", value = "fid") String fid,
                                  @RequestParam(defaultValue = "", value = "state") String state,
                                  @RequestParam(defaultValue = "", value = "agreed") String agreed,
                                  @RequestParam(defaultValue = "", value = "auditcomment") String auditcomment,
                                  @RequestParam(defaultValue = "", value = "fnumber") String fnumber,
                                  @RequestParam(defaultValue = "", value = "studentid[]") String[] studentid,
                                  @RequestParam(defaultValue = "", value = "cftlyy[]") String[] cftlyy,
                                  @RequestParam(defaultValue = "", value = "cflcsjid") String cflcsjid) {

        Dropexercisetwo dropexercisetwo = new Dropexercisetwo();
        User user=(User)request.getSession().getAttribute("user");
        dropexercisetwo.setFid(fid);
        dropexercisetwo.setFnumber(fnumber);
        dropexercisetwo.setFauditorid(user.getFid());
        return dropexerciseTwoService.examine(dropexercisetwo, state, agreed, auditcomment, cflcsjid, studentid, cftlyy);
    }

    /**
     * @Author lcx
     * @Date 2018/2/27 0027 上午 11:49
     * 提交
     */
    @RequestMapping(value = "/queryDropexercisetwoSubmit")
    @ResponseBody
    public ServerResponse submit(HttpServletRequest request,
                                 @RequestParam(defaultValue = "", value = "fnumber") String fnumber,
                                 @RequestParam(defaultValue = "", value = "fid") String fid) {
        Axamine axamine = new Axamine();
        Dropexercisetwo dropexercisetwo = new Dropexercisetwo();

        dropexercisetwo.setFid(fid);
        /*dropexercisetwo.setFauditorid(((User) request.getSession().getAttribute("user")).getFid());*/
        dropexercisetwo.setCfbillstate(Long.valueOf("4"));
        dropexercisetwoMapper.updateByPrimaryKeySelective(dropexercisetwo);

        dropexerciseTwoService.addLog(dropexercisetwo.getFid(), "1");

        return axamine.submissionProcess(String.valueOf(fnumber));
    }

    @RequestMapping("/queryDropexercisetwoRegXls")
    public String queryDropexercisetwoRegXls(HttpServletRequest request, HttpServletResponse response,
                                             @RequestParam(defaultValue = "", value = "fnumber") String fnumber,
                                             @RequestParam(defaultValue = "", value = "fdescription") String fdescription,
                                             @RequestParam(defaultValue = "", value = "cfstudentname") String cfstudentname,
                                             @RequestParam(defaultValue = "", value = "beginTime") String beginTime,
                                             @RequestParam(defaultValue = "", value = "endTime") String endTime) {

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");

        //头部数据
        List<Object> data = new ArrayList<>();
        String head[] = {"单据编号", "业务日期", "参考消息", "审核人名称", "制单人名称", "单据状态", "学员", "学员编号", "身份证号码", "手机",
                "电话", "教练", "练车时间", "练车天数", "退练原因", "几人几车"
        };
        //长度
        Integer length[] = {8500, 5000, 6000, 3000, 3000, 3000, 3000, 6000, 6000, 6000,
                3000, 3000, 3000, 3000, 3000, 3000};

        List<Dropexercisetwoentry> dropexercisetwoentryList = dropexerciseTwoService.selectDropexercisetworegAsXls(fnumber, fdescription, cfstudentname, beginTime, endTime, user.getFcompanyid());


        for (Dropexercisetwoentry dropexercisetwoentry : dropexercisetwoentryList) {
            data.add(dropexercisetwoentry.getFnumber());
            data.add(dropexercisetwoentry.getFbizdate());
            data.add(dropexercisetwoentry.getFdescription());
            data.add(dropexercisetwoentry.getCheckName());
            data.add(dropexercisetwoentry.getCreateName());
            data.add(stateToString.billsState(dropexercisetwoentry.getCfbillstate()));
            data.add(dropexercisetwoentry.getCfstudentName());
            data.add(dropexercisetwoentry.getCfstudentno());
            data.add(dropexercisetwoentry.getCfidcardno());
            data.add(dropexercisetwoentry.getCfmobile());
            data.add(dropexercisetwoentry.getCfphone());
            data.add(dropexercisetwoentry.getCfcoachName());
            data.add(dropexercisetwoentry.getCflcts());//练车时间
            data.add(dropexercisetwoentry.getCflcts());//练车天数
            data.add(dropexercisetwoentry.getCftlyy());//退练原因
            data.add(dropexercisetwoentry.getCfcarpeoplenum());//几人几车
        }

        try {
            //导出Excel
            CommonExport.importExcel(response, "科目二退练" + TimeFormat.getNowTime2() + ".xls", "科目二退练", data, head, length);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "redirect:/DrivingSys/queryDropexercisetwo/look.action?state=first";
    }
}
